package com.ganinfo.file.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.etoon.util.EncryptUtil;
import com.ganinfo.common.Result;
import com.ganinfo.common.aliyun.AliOSSTool;
import com.ganinfo.common.constant.PropertiesConstant;
import com.ganinfo.common.controller.BaseController;
import com.xiaoleilu.hutool.convert.Convert;

@Controller
@RequestMapping("/file")
public class FileController extends BaseController{
	
	/**
	 * @Title:       fileuploadforad
	 * @Description: 文件上传操作
	 * @param request
	 * @param resp
	 * @return
	 * @return:      String
	 */
	@RequestMapping(value="/fileupload",method=RequestMethod.POST,produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public void fileuploadforad (HttpServletRequest request,HttpServletResponse resp){
		
		resp.setContentType("text/json;charset=UTF-8");
		//最大文件限制  100M
		long maxSize = 100000000;
				
		//上传文件的后缀名：gif,jpg,jpeg,png,bmp
		/*HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");*/
						
		DefaultMultipartHttpServletRequest mrequest= (DefaultMultipartHttpServletRequest)request;
		Map<String, MultipartFile> map=mrequest.getFileMap();
		Collection<MultipartFile> c = map.values();
		Iterator<MultipartFile> it = c.iterator();
		
		List<String> fileAddressList=new ArrayList<>();//返回图片的key和图片地址
		//上传到阿里云上的key
		StringBuffer returnString=new StringBuffer();
		for (;it.hasNext();){
			String key = null;
			//上传文件对象
			CommonsMultipartFile file=(CommonsMultipartFile) it.next();
			if(!file.isEmpty()){
				long fileSize = file.getSize();
				String fileName = file.getOriginalFilename();
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				
				if(fileSize==0){
					String result = new Result(0,null,"上传文件为空！",null).toJson();
					PrintWriter out;
					try {
						out = resp.getWriter();
						out.write(result);
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
				if(fileSize > maxSize){
					//100M
					String result = new Result(0,null,"上传文件尺寸过大！",null).toJson();
					PrintWriter out;
					try {
						out = resp.getWriter();
						out.write(result);
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				/*if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
					return new Result(0,null,"上传图片后缀名不正确！",null).toJson();
				}*/
						
				//flag为是否存本地，true存本地，false存阿里云（接通后只存阿里云）
				boolean flag = false;
				if(flag){
					//存本地
					//已废弃
				}else{
					//存到云服务上，返回对应的url
					try {
						//原图上传
						InputStream reader = file.getInputStream();
						key = getKey(reader,fileExt);
						  
						//生成缩略图再上传
						//uploadThumbnailImage(file,key+"_3" ,fileExt);
						//fileAddressList.add(key);
						returnString.append(key);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
					 
		}
		if(!"".equals(returnString.toString())){
			this.logForResult(new Result(200,fileAddressList,"上传成功！",null));
			String result = new Result(200,returnString.toString(),"上传成功!",null).toJson();
			PrintWriter out;
			try {
				out = resp.getWriter();
				out.write(result);
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			String result = new Result(0,null,"上传失败，请重试！",null).toJson();
			PrintWriter out;
			try {
				out = resp.getWriter();
				out.write(result);
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
	public String getFolderPath(String folder, String key, int type) {
		String path = "";
		if (key.length() > 0) {
			try {
				String f1 = key.substring(0, 2);
				String f2 = key.substring(2, 4);
				String[] fileType = new String[] { "file", "img", "audio", "video", "idcardimg" };
				path = String.format("%s/%s/%s/%s/", folder, fileType[type], f1, f2);
			} catch (Exception e) {
				e.printStackTrace();
				path = "";
			}

		}

		return path;
	}
	
	//suffix:读取的文件的后缀名，例如：png等
	private String getKey(InputStream reader,String suffix){
		String returnkey = null;
		try {
			//available:可以从流中读取的字节数
			int len = reader.available();
			byte[] btarr = new byte[len];
			
			//将从流中读取的字节储存在缓冲区btarr中
			reader.read(btarr);
			
			//将读取的信息进行加密
			String key = EncryptUtil.EncryptMD5Byte(btarr);
			
			
			String webpath = PropertiesConstant.CONFIG_PRO.getStr("filewebpath");
			//type=0代表文件
			int type = 1;
			
			//获得文件的缓存路径
			String path = getFolderPath(webpath, key, type);
			
			//通过日志记录文件广告信息
			//SystemConfig.log.log(String.format("file upload ,type:%s  path:%s",type,path));
			
			
			String uploadkey = path+key;
			
			String aliosskey = PropertiesConstant.CONFIG_PRO.getStr("aliosskey");
			String secret = PropertiesConstant.CONFIG_PRO.getStr("aliosssecret");
			String endpoint= PropertiesConstant.CONFIG_PRO.getStr("aliossendpoint");
			String defaultbucket= PropertiesConstant.CONFIG_PRO.getStr("defaultbucket");
			String innerendpoint= PropertiesConstant.CONFIG_PRO.getStr("aliossendpointinternal");
			String isinserver=PropertiesConstant.CONFIG_PRO.getStr("isinserver");
			boolean isinECS=false;
			if("true".equals(isinserver)){
				isinECS=true;
			}
			try {
				boolean flag=AliOSSTool.init(aliosskey, secret, endpoint, defaultbucket,innerendpoint,isinECS);
				System.out.println("连接阿里OSS服务："+(flag?"成功":"失败"));
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(String.format("连接阿里OSS服务出错：%1$s.", e.getMessage()));
			}
			
			//上传到阿里云上
			AliOSSTool.getInstance().putObject(uploadkey, btarr,suffix);
			returnkey = uploadkey.replace("files/img/", "");
    	} catch (IOException e) {
			e.printStackTrace();
		}
		//返回key
		return returnkey;
	}
	
	
	static public void main (String args[]){
		List<String> fileAddressList=new ArrayList<>();
		fileAddressList.add("12231");
		fileAddressList.add("8567967");
		System.out.println(Convert.toStr(fileAddressList));
//		FileController a = new FileController();
//		String key="501C4E07BDA06A7ABA51DA3A60530C9B";
//		String path=a.getFolderPath("files", key, 1);
//		System.out.println(path);
//		String returnkey = path+key;
//		System.out.println(returnkey);
//		String aa = returnkey.replace("files/img/", "");
//		System.out.println(aa);
		//最后返回的：50/1C/501C4E07BDA06A7ABA51DA3A60530C9B
	}
}
